import React from 'react';
import { Tree, Spin } from 'antd';
import { connect } from 'umi';

const { TreeNode } = Tree;
class DeptTree extends React.Component<any, any> {
    constructor(props: any) {
        super(props);
        this.state = {
            loading: false,
            dataSource: [],
        }
    }
    onSelect = (selectedKeys: any, info: any) => {
        this.props.setCurrent(info.node);
    };
    onDbSelect = (selectedKeys:any, info:any) => {
    };
    componentDidMount() {
        this.props.onRef(this)
        this.fetchData();
    }
    fetchData = () => {
        this.props.dispatch({
            type: 'Abp/getTreeList',
            payload: {},
            control: 'Department',
        }).then(() => {
            this.setState({ dataSource: this.props.response.result });
        });
    }
    onCheck = (checkedKeys:any, info:any) => {
        this.props.setParent(info.node);
    };
    mapData = (children:any) => {
        if (children && Array.isArray(children)) {
            return children.map((ele) => {
                if (ele.children && Array.isArray(ele.children)) {
                    return <TreeNode title={ele.deptName} key={ele.id}>
                        {this.mapData(ele.children)}
                    </TreeNode>
                } else {
                    return <TreeNode title={ele.deptName} key={ele.id} />
                }
            })
        }
        return []
    }
    render() {
        const { dataSource } = this.state;
        return (
            <div>
                {
                    dataSource && dataSource.length ? (
                        <Tree
                            checkable
                            defaultExpandAll
                            onSelect={this.onSelect}
                            onDoubleClick={this.onDbSelect}
                            onCheck={this.onCheck}
                        >
                            {dataSource.map((data:any) => (
                                <TreeNode title={data.deptName} key={data.id}>
                                    {this.mapData(data.children)}
                                </TreeNode>
                            ))}
                        </Tree>
                    ) : (
                            <Spin />
                        )
                }
            </div>
        )
    }
}
export default connect(({ Abp, Department }: API.IConnectState) => ({
    response: Abp.response,
    currentUser: Abp.currentUser,
    departments: Department.departments,
}))(DeptTree);